package com.eye.catcher.controller;


import com.alibaba.fastjson.JSONObject;
import com.eye.catcher.constants.SbCode;
import com.eye.catcher.entity.TYwDaFieldInfo;
import com.eye.catcher.entity.TYwDaObserveInfo;
import com.eye.catcher.param.CommonResponse;
import com.eye.catcher.param.ResponseData;
import com.eye.catcher.param.ResponseUtil;
import com.eye.catcher.rabbit.MQDto;
import com.eye.catcher.service.generate.ITYwDaFieldInfoService;
import com.eye.catcher.service.generate.ITYwDaObserveInfoService;
import com.eye.catcher.system.yw.Info.param.FieldInfoDto;
import com.eye.catcher.system.yw.Info.param.FieldInfoPage;
import com.eye.catcher.system.yw.Info.param.ObserveInfoDto;
import com.eye.catcher.system.yw.Info.param.ObserveInfoPage;
import com.eye.catcher.utils.DownloadUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;

/**
 * <p>
 * 观测信息表 前端控制器
 * </p>
 *
 * @author huzhiwei
 * @since 2022-05-12
 */
@Slf4j
@RestController
@RequestMapping("/eyeCatcher-system/observe-info")
public class TYwDaObserveInfoController extends TSysDaBaseController {
    private final static String MODULE_CODE = "/observe-info";
    private final static String MODULE_NAME = "观测信息";


    @Autowired
    private ITYwDaObserveInfoService infoService;


    //校验 占比
    //如果 同一个基地 ，五个田地 ，一个观测期  ，前四个+ 当前  不等于100% 提示 有问题
    @PostMapping("/checkSameProportion")
    @ResponseBody
    public ResponseData checkSameProportion(
            @RequestParam(value = "baseId", required = false) String baseId,
            @RequestParam(value = "observeId", required = false) String observeId,
            @RequestParam(value = "sameProportion", required = false) String sameProportion,
            @RequestParam(value = "observeName", required = false) String observeName
    ) {
        String methodCode = "/checkSameProportion";
        MQDto mqDto = null;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("baseId",baseId);
        jsonObject.put("observeId",observeId);
        jsonObject.put("sameProportion",sameProportion);
        jsonObject.put("observeName",observeName);
        try{
            String userId = getLoginUserId();
            mqDto = new MQDto(methodCode,userId,MODULE_CODE,MODULE_NAME,getClass(),
                    SbCode.OPERATION_QUERY,jsonObject.toString(),null,null);
            this.sendInitRabbitMqLog(mqDto);
            String msg = this.infoService.checkSameProportion(baseId,observeId,sameProportion,observeName);
            if(null == msg){
                commonResponse = CommonResponse.success();
            }else{
                commonResponse = CommonResponse.getInstance();
                commonResponse.setCode(SbCode.SYSTEM_ERROR.getCode());
                commonResponse.setMsg(msg);
                commonResponse.setData((Object)null);
            }
            log.info(methodCode, commonResponse.toString());
        }catch (Exception e){
            e.printStackTrace();
            this.sendAbnormalRabbitMqLog(mqDto.addException(e));
            log.error(methodCode+"/n", e);
            commonResponse = CommonResponse.error(e);
        }finally {
            this.sendFinishRabbitMqLog(mqDto.addResult(commonResponse));
        }
        return new ResponseUtil<>().setData(commonResponse);
    }


    @PostMapping("/addObserveInfo")
    @ResponseBody
    public ResponseData addObserveInfo(@RequestBody TYwDaObserveInfo info) {
        String methodCode = "/addObserveInfo";
        MQDto mqDto = null;
        try{
            String userId = getLoginUserId();
            mqDto = new MQDto(methodCode,userId,MODULE_CODE,MODULE_NAME,getClass(),
                    SbCode.OPERATION_ADD,info.toString(),null,null);
            this.sendInitRabbitMqLog(mqDto);
            boolean checkTypical = true;
            if(StringUtils.isNotEmpty(info.getTypicalUrl()) &&
                    info.getTypicalUrl().split(",").length > 5){
                    checkTypical = false;
            }
            if(checkTypical){
                info.setCreateUserId(userId);
                if(!this.infoService.isEmpty(info)){
                    this.infoService.addObserveInfo(info);
                    commonResponse = CommonResponse.success();
                }else{
                    CommonResponse response = CommonResponse.getInstance();
                    response.setCode(SbCode.SYSTEM_ERROR.getCode());
                    response.setMsg("观测期重复");
                    response.setData(null);
                }
            }else{
                CommonResponse response = CommonResponse.getInstance();
                response.setCode(SbCode.SYSTEM_ERROR.getCode());
                response.setMsg("最多能上传5张");
                response.setData(null);
            }
            log.info(methodCode, commonResponse.toString());
        }catch (Exception e){
            e.printStackTrace();
            this.sendAbnormalRabbitMqLog(mqDto.addException(e));
            log.error(methodCode+"/n", e);
            commonResponse = CommonResponse.error(e);
        }finally {
            this.sendFinishRabbitMqLog(mqDto.addResult(commonResponse));
        }
        return new ResponseUtil<>().setData(commonResponse);
    }
    @PostMapping("/editObserveInfo")
    @ResponseBody
    public ResponseData editObserveInfo(@RequestBody TYwDaObserveInfo info) {
        String methodCode = "/editObserveInfo";
        MQDto mqDto = null;
        try{
            String userId = getLoginUserId();
            mqDto = new MQDto(methodCode,userId,MODULE_CODE,MODULE_NAME,getClass(),
                    SbCode.OPERATION_EDIT,info.toString(),null,null);
            this.sendInitRabbitMqLog(mqDto);
            boolean checkTypical = true;
            if(StringUtils.isNotEmpty(info.getTypicalUrl()) &&
                    info.getTypicalUrl().split(",").length > 5){
                checkTypical = false;
            }
            if(checkTypical) {
                info.setUpdateUserId(userId);
                this.infoService.editObserveInfo(info);
                commonResponse = CommonResponse.success();
            }else{
                CommonResponse response = CommonResponse.getInstance();
                response.setCode(SbCode.SYSTEM_ERROR.getCode());
                response.setMsg("最多能上传5张");
                response.setData(null);
            }
            log.info(methodCode, commonResponse.toString());
        }catch (Exception e){
            e.printStackTrace();
            this.sendAbnormalRabbitMqLog(mqDto.addException(e));
            log.error(methodCode+"/n", e);
            commonResponse = CommonResponse.error(e);
        }finally {
            this.sendFinishRabbitMqLog(mqDto.addResult(commonResponse));
        }
        return new ResponseUtil<>().setData(commonResponse);
    }

    /**
     * @author huzhiwei
     * @param ids 项目id  多个id  ， 分割
     * @return
     */
    @PostMapping("/deleteObserveInfoByIds")
    @ResponseBody
    public ResponseData deleteObserveInfoByIds(@RequestParam(value = "ids") String ids) {
        String methodCode = "/deleteObserveInfoByIds";
        MQDto mqDto = null;
        try{
            mqDto = new MQDto(methodCode,getLoginUserId(),MODULE_CODE,MODULE_NAME,getClass(),
                    SbCode.OPERATION_DELETE,"ids: "+ids,null,null);
            this.sendInitRabbitMqLog(mqDto);
            this.infoService.deleteByIds(ids);
            commonResponse = CommonResponse.success();
            log.info(methodCode, commonResponse.toString());
        }catch (Exception e){
            e.printStackTrace();
            this.sendAbnormalRabbitMqLog(mqDto.addException(e));
            log.error(methodCode+"/n", e);
            commonResponse = CommonResponse.error(e);
        } finally {
            this.sendFinishRabbitMqLog(mqDto.addResult(commonResponse));
        }
        return new ResponseUtil<>().setData(commonResponse);
    }
    @PostMapping("/getAllList")
    @ResponseBody
    public ResponseData getAllList(@RequestBody ObserveInfoDto observeInfo) {
        String methodCode = "/getAllList";
        MQDto mqDto = null;
        try{
            String userId = getLoginUserId();
            mqDto = new MQDto(methodCode,userId,MODULE_CODE,MODULE_NAME,getClass(),
                    SbCode.OPERATION_QUERY,observeInfo.toString(),null,null);
            this.sendInitRabbitMqLog(mqDto);
            observeInfo.setUserId(userId);
            commonResponse = CommonResponse.success();
            commonResponse.setData(this.infoService.getAllList(observeInfo));
            log.info(methodCode, commonResponse.toString());
        }catch (Exception e){
            e.printStackTrace();
            this.sendAbnormalRabbitMqLog(mqDto.addException(e));
            log.error(methodCode+"/n", e);
            commonResponse = CommonResponse.error(e);
        }finally {
            this.sendFinishRabbitMqLog(mqDto.addResult(commonResponse));
        }
        return new ResponseUtil<>().setData(commonResponse);
    }

    @PostMapping("/getPageList")
    @ResponseBody
    public ResponseData getPageList(@RequestBody ObserveInfoDto observeInfo) {
        String methodCode = "/getPageList";
        MQDto mqDto = null;
        try{
            String userId = getLoginUserId();
            mqDto = new MQDto(methodCode,userId,MODULE_CODE,MODULE_NAME,getClass(),
                    SbCode.OPERATION_QUERY,observeInfo.toString(),null,null);
            this.sendInitRabbitMqLog(mqDto);
            observeInfo.setUserId(userId);
            commonResponse = CommonResponse.success();
            commonResponse.setData(
                    this.infoService.getPageList(
                            ObserveInfoPage.builder()
                                    .observeInfo(observeInfo)
                                    .page(this.getPageInfo(observeInfo))
                                    .build()
                    )
            );
            log.info(methodCode, commonResponse.toString());
        }catch (Exception e){
            e.printStackTrace();
            this.sendAbnormalRabbitMqLog(mqDto.addException(e));
            log.error(methodCode+"/n", e);
            commonResponse = CommonResponse.error(e);
        }finally {
            this.sendFinishRabbitMqLog(mqDto.addResult(commonResponse));
        }
        return new ResponseUtil<>().setData(commonResponse);
    }

    //文件上传
    @RequestMapping(path = "/uploadYwFile")
    public @ResponseBody
    ResponseData uploadYwFile(@RequestParam("file") MultipartFile file) {
        String methodCode = "/uploadYwFile";
        MQDto mqDto = null;
        try{
            mqDto = new MQDto(methodCode,getLoginUserId(),MODULE_CODE,MODULE_NAME,getClass(),
                    SbCode.OPERATION_UPLOAD,null,null,null);
            this.sendInitRabbitMqLog(mqDto);
            String path = this.infoService.uploadYwFile(file);
            commonResponse = CommonResponse.success();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("path",path);
            commonResponse.setData(jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
            this.sendAbnormalRabbitMqLog(mqDto.addException(e));
            log.error(methodCode+"/n", e);
            commonResponse = CommonResponse.error(e);
        } finally {
            this.sendFinishRabbitMqLog(mqDto.addResult(commonResponse));
        }
        return new ResponseUtil<>().setData(commonResponse);
    }
    //文件预览
    @RequestMapping(path = "/previewYwFile")
    public @ResponseBody
    ResponseData previewYwFile(HttpServletRequest request, HttpServletResponse response,
                               @RequestParam(value = "typicalUrl", required = false) String typicalUrl) {
        String methodCode = "/previewYwFile";
        MQDto mqDto = null;
        try{
            mqDto = new MQDto(methodCode,getLoginUserId(),MODULE_CODE,MODULE_NAME,getClass(),
                    SbCode.OPERATION_PREVIEW,"typicalUrl:"+typicalUrl,null,null);
            this.sendInitRabbitMqLog(mqDto);
            String msg = this.infoService.previewYwFile(request,response,typicalUrl);
            if (StringUtils.isNotEmpty(msg)) {
                commonResponse = CommonResponse.getInstance();
                commonResponse.setCode(SbCode.SYSTEM_ERROR.getCode());
                commonResponse.setMsg(msg);
                commonResponse.setData(null);
            } else {
                commonResponse = CommonResponse.success();
            }
        } catch (Exception e) {
            e.printStackTrace();
            this.sendAbnormalRabbitMqLog(mqDto.addException(e));
            log.error(methodCode+"/n", e);
            commonResponse = CommonResponse.error(e);
        } finally {
                this.sendFinishRabbitMqLog(mqDto.addResult(commonResponse));
        }
        return new ResponseUtil<>().setData(commonResponse);
    }

    //文件预览
    @RequestMapping(path = "/dowloadYwFile")
    public @ResponseBody
    ResponseData dowloadYwFile(HttpServletRequest request, HttpServletResponse response,
                               @RequestParam(value = "typicalUrl", required = false) String typicalUrl,
                               @RequestParam(value = "fileName", required = false) String fileName) {
        String methodCode = "/dowloadYwFile";
        MQDto mqDto = null;
        try{
            mqDto = new MQDto(methodCode,getLoginUserId(),MODULE_CODE,MODULE_NAME,getClass(),
                    SbCode.OPERATION_DOWLOAD,"typicalUrl:"+typicalUrl,null,null);
            this.sendInitRabbitMqLog(mqDto);
            String msg = this.infoService.dowloadYwFile(request,response,typicalUrl,fileName);
            if (StringUtils.isNotEmpty(msg)) {
                commonResponse = CommonResponse.getInstance();
                commonResponse.setCode(SbCode.SYSTEM_ERROR.getCode());
                commonResponse.setMsg(msg);
                commonResponse.setData(null);
            } else {
                commonResponse = CommonResponse.success();
            }
        } catch (Exception e) {
            e.printStackTrace();
            this.sendAbnormalRabbitMqLog(mqDto.addException(e));
            log.error(methodCode+"/n", e);
            commonResponse = CommonResponse.error(e);
        } finally {
            this.sendFinishRabbitMqLog(mqDto.addResult(commonResponse));
        }
        return new ResponseUtil<>().setData(commonResponse);
    }

    /**
     * 导出
     */
    @RequestMapping(path = "/export")
    public @ResponseBody
    ResponseData export(HttpServletRequest request, HttpServletResponse response,
                        @RequestParam(value = "token", required = false) String token) {
        String methodCode = "/export";
        MQDto mqDto = null;
        try{
            String userId = getLoginUserId(token);
            mqDto = new MQDto(methodCode,userId, MODULE_CODE, MODULE_NAME, getClass(),
                    SbCode.OPERATION_DOWLOAD, null, null, null);
            this.sendInitRabbitMqLog(mqDto);
            String msg = this.infoService.export(userId,request,response);
            if (StringUtils.isNotEmpty(msg)) {
                commonResponse = CommonResponse.getInstance();
                commonResponse.setCode(SbCode.SYSTEM_ERROR.getCode());
                commonResponse.setMsg(msg);
                commonResponse.setData(null);
            } else {
                commonResponse = CommonResponse.success();
            }
        } catch (Exception e) {
            e.printStackTrace();
            this.sendAbnormalRabbitMqLog(mqDto.addException(e));
            log.error(methodCode+"/n", e);
            commonResponse = CommonResponse.error();
        } finally {
            this.sendFinishRabbitMqLog(mqDto.addResult(commonResponse));
        }
        return new ResponseUtil<>().setData(commonResponse);
    }
}
